package cn.shop.merchant.controller.media;

import cn.dev33.satoken.stp.StpUtil;
import cn.shop.merchant.model.media.News;
import cn.shop.merchant.service.NewsService;
import cn.shop.utils.ApiResult;
import cn.shop.utils.annotation.OperationLog;
import cn.shop.utils.enums.OperationType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

import static cn.shop.utils.constant.Constant.UID;

/**
 * @author : 李一涵
 * @date : Created in 2021-11-4 11:02
 * @description : 新闻controller
 */
@RestController
@RequestMapping("/news")
public class NewsController {

    @Resource
    private NewsService newsService;

    /**
     * 获取新闻列表
     *
     * @param current 当前页
     * @param size 每页记录数
     * @param order 排序
     * @param title 标题
     * @return 返回结果
     */
    @GetMapping("/list")
    public ApiResult<Map<String, Object>> list(int current, int size, String title,
                                               @RequestParam(defaultValue = "-1") int order) {
        long uid = StpUtil.getSession().getLong(UID);
        Map<String, Object> data = newsService.list(uid, current, size, title, order);
        return ApiResult.success(data);
    }

    /**
     * 新增新闻
     *
     * @param news 新闻
     * @return 返回结果
     */
    @PostMapping("")
    @OperationLog(desc = "新增新闻", type = OperationType.CREATE)
    public ApiResult<Map<String, Object>> insert(@Validated @RequestBody News news) {
        if (news == null) {
            throw new RuntimeException("新闻对象为空");
        }
        boolean isSuccess = newsService.save(news);
        return ApiResult.result(isSuccess);
    }

    /**
     * 更新新闻
     *
     * @param news 新闻
     * @return 返回结果
     */
    @PutMapping("")
    @OperationLog(desc = "修改新闻", type = OperationType.UPDATE)
    public ApiResult<Map<String, Object>> update(@RequestBody News news) {
        long uid = StpUtil.getSession().getLong(UID);
        if (news == null) {
            throw new RuntimeException("新闻对象为空");
        }
        boolean isSuccess = newsService.update(news, uid);
        return ApiResult.result(isSuccess);
    }

    /**
     * 删除新闻
     *
     * @param ids 编号
     * @return 返回结果
     */
    @DeleteMapping("/delete/{ids}")
    @OperationLog(desc = "删除新闻", type = OperationType.DELETE)
    public ApiResult<Map<String, Object>> delete(@PathVariable("ids") long[] ids) {
        long uid = StpUtil.getSession().getLong(UID);
        boolean isSuccess = newsService.delete(ids, uid);
        return ApiResult.result(isSuccess);
    }

    /**
     * 获取新闻信息
     *
     * @param id 编号
     * @return 返回结果
     */
    @GetMapping("/edit/{id}")
    public ApiResult<Map<String, Object>> info(@PathVariable("id") long id) {
        long uid = StpUtil.getSession().getLong(UID);
        Map<String, Object> data = newsService.info(id, uid);
        return ApiResult.success(data);
    }
}
